package com.dx.wx.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dx.wx.service.DxOrderService;
import com.dx.wx.service.DxUserService;
import com.dx.wx.service.DxWxAppService;
import com.dx.wx.util.WxPayUtil;
import com.ejlchina.data.Array;
import com.ejlchina.data.Mapper;
import com.ejlchina.okhttps.OkHttps;
import com.yf.dao.WxConfigDao;
import com.yf.entity.WxConfigEntity;
import com.yf.response.RRException;
import com.yf.util.WxUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class DxWxAppServiceImpl implements DxWxAppService {

    public WxMaService service;

    @Autowired
    private WxConfigDao wxConfigDao;

    private WxConfigEntity wxConfigEntity;

    private WxConfigEntity bbConfigEntity;

    @Override
    public WxMaJscode2SessionResult getWxId(String code, String appId) {
        try {
            WxMaJscode2SessionResult result = wxService(appId).getUserService().getSessionInfo(code);
            return result;
        } catch (WxErrorException e) {
            throw new RRException("获取用户信息错误");
        }
    }

    @Override
    public WxMaPhoneNumberInfo getWxPhone(String code) {
        try {
            WxMaPhoneNumberInfo phoneNumberInfo = wxService().getUserService().getNewPhoneNoInfo(code);
            return phoneNumberInfo;
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new RRException("获取用户手机信息错误");
        }
    }

    /**
     * 上动销配置
     * @return
     */
    private WxConfigEntity getWxAppConfig() {
        if (this.wxConfigEntity == null) {
            this.wxConfigEntity = wxConfigDao.findByType(2);
        }
        return this.wxConfigEntity;
    }


    /**
     * 蹦蹦配置
     * @return
     */
    private WxConfigEntity getBBAppConfig(){
        if (this.bbConfigEntity == null) {
            this.bbConfigEntity = wxConfigDao.findByType(3);
        }
        return this.bbConfigEntity;
    }

    private WxMaService wxService(String appId) {
        if (this.service == null) {
            WxMaService service = new WxMaServiceImpl();
            //配置1
            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
            config.setAppid(getWxAppConfig().getAppId());
            config.setSecret(getWxAppConfig().getSecret());
            //配置2
            WxMaDefaultConfigImpl config1 = new WxMaDefaultConfigImpl();
            config1.setAppid(getBBAppConfig().getAppId());
            config1.setSecret(getBBAppConfig().getSecret());
            Map map = new HashMap();
            map.put(config.getAppid(),config);
            map.put(config1.getAppid(),config1);
            service.setMultiConfigs(map);
            this.service = service;
        }
        if(appId==null){ //取默认的
            appId = getWxAppConfig().getAppId();
        }
        //如果传入了 就切换 他是线程的 就切换一次
        service.switchover(appId);
        return service;
    }

    //取默认值
    private WxMaService wxService(){
        return wxService(null);
    }


    @Resource
    @Lazy
    private DxUserService dxUserService;


    @Override
    public void sendMoney(Map map) {
        //ID
        String orderId = (String) map.get("_id");
        //订单编号
        String originOrderNo = (String) map.get("name");
        String orderNo = originOrderNo.replace("-", "");
        //晒单人姓名
        String name = (String) map.get("field_j9z4g__c");
        Double amount = (Double) map.get("order_amount");
        //晒单人手机号
        String phone = (String) map.get("field_r1V1t__c");
        //晒单类型 record_DsRx3__c 集体晒单  default__c 个人晒单
        String type = (String) map.get("record_type");
        WxConfigEntity configEntity = getWxAppConfig();
        JSONObject payJson = new JSONObject();
        payJson.put("appid", configEntity.getAppId());
        payJson.put("out_batch_no", orderNo);
        payJson.put("batch_name", name + " " + phone);
        payJson.put("batch_remark", originOrderNo);
//        int sumAmount = 30;
        //10:1积分 兑换
        int sumAmount = new BigDecimal(amount * 100 / 10).intValue();
        payJson.put("total_amount", sumAmount);
        JSONArray array = new JSONArray();
        //红包类型
        Mapper userMapper = dxUserService.findByMobile(phone);
        String sendType = userMapper.getString("field_Ctvjm__c");
        //个人晒单 或者晒单有礼
        if ((type.equals("default__c")||type.equals("record_FL122__c"))||(sendType!=null&&sendType.equals("24plzuBgu"))) {//个人晒单 晒单类型是晒单人
            //晒单人OpenId
            String openId = (String) map.get("wx_openid__c");
            payJson.put("total_num", 1);//发起总次数
            JSONObject detail = new JSONObject();
            detail.put("out_detail_no", orderNo);
//            if(type.equals("record_FL122__c")){//晒单有礼
//                Mapper gift = dxHomeService.gift();
//                int temAmount = new BigDecimal(gift.getDouble("field_A416s__c")*100).intValue();
//                detail.put("transfer_amount",temAmount);
//            }else {
//                detail.put("transfer_amount", sumAmount);
//            }
            detail.put("transfer_amount", sumAmount);
            detail.put("transfer_remark", originOrderNo);
            detail.put("openid", openId);
            array.add(detail);
        } else { //集体晒单
            Array details = dxOrderService.findDetailByOrderId(orderId);
            payJson.put("total_num", details.size());//发起总次数
            details.forEach((index, data) -> {
                Mapper mapper = data.toMapper();
                //微信ID
                String openId = mapper.getString("field_95S9w__c");
                //小计
                Double total = mapper.getDouble("subtotal");
                total = total * 100 / 10;
                JSONObject detail = new JSONObject();
                detail.put("out_detail_no", orderNo + index);
                detail.put("transfer_amount", total);
                detail.put("transfer_remark", originOrderNo);
                detail.put("openid", openId);
                array.add(detail);
            });
        }
        payJson.put("transfer_detail_list", array);
        String keyPath = this.getClass().getClassLoader().getResource("apiclient_cert.p12").getPath();
        try {
            String token = WxPayUtil.getToken(keyPath, wxConfigEntity.getMchId(), "1BA1190A294A430EE1C88FD41C7CFED6402ED9BC", WxUtil.getNoncestr(), "POST", url, payJson.toString());
            String auth = WxPayUtil.getAuthorization(token);
            Mapper mapper = OkHttps.getHttp().async(url).addHeader("Authorization", auth).addHeader("Accept", "application/json").addHeader("Wechatpay-Serial", "1BA1190A294A430EE1C88FD41C7CFED6402ED9BC").bodyType(OkHttps.JSON).setBodyPara(payJson.toString()).post().getResult().getBody().toMapper();
            System.out.println(mapper.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    @Resource
    @Lazy
    private DxOrderService dxOrderService;

    //发起商家转账API
    private String url = "https://api.mch.weixin.qq.com/v3/transfer/batches";


    @Override
    public void createQrCode(Long phone, int role, int workType, HttpServletResponse response, String appId) {
        String scene = String.format("phone=%s&role=%s", phone, role);
        String page = "pages/index/index";
        try {
            File file = wxService(appId).getQrcodeService().createWxaCodeUnlimit(scene, page);
            try {
                BufferedImage bufferedImage = ImageIO.read(file);
                ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/ocr/ocr.printedText.html
     *
     * @param file
     * @return
     */
    @Override
    public Mapper orc(MultipartFile file) {
        String url = "https://api.weixin.qq.com/cv/ocr/comm?access_token=%s";
        try {
            url = String.format(url, wxService().getAccessToken());
            Mapper mapper = OkHttps.sync(url).addFilePara("img", "jpg", file.getBytes()).post().getBody().toMapper();
            return mapper;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
